package net.sudot.chess.business.controller.web;

import net.sudot.chess.business.controller.AbstractBaseController;
import net.sudot.chess.business.dto.RankDTO;
import net.sudot.chess.business.service.RankService;
import net.sudot.chess.config.Cycle;
import net.sudot.chess.config.SystemProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 排行榜
 *
 * @author tangjialin on 2018-05-07.
 */
@Controller
@RequestMapping(value = "/rank")
public class RankController extends AbstractBaseController {
    @Resource
    private RankService rankService;
    @Resource
    private SystemProperties systemProperties;

    /**
     * 排行榜首页
     *
     * @return 返回排行榜视图
     */
    @GetMapping
    public String index() {
        return "rank/index";
    }

    /**
     * 获取排行榜信息
     *
     * @return 返回排行榜信息
     */
    @PostMapping("/list")
    @ResponseBody
    public List<RankDTO> list() {
        List<RankDTO> rank;
        List<Long> userIds = new ArrayList<>(10);
        Map<Long, RankDTO> rankingListDTOMap = new HashMap<>();
        // 周排行榜
        {
            Cycle cycle = systemProperties.getRankCycle();
            Cycle.CycleCalc cycleCalc = new Cycle.CycleCalc(LocalDate.now(), cycle);
            Instant start = cycleCalc.getStartDateWidth();
            Instant end = cycleCalc.getEndDateWidth();
            rank = rankService.findList(start, end);
            for (RankDTO rankDTO : rank) {
                rankDTO.setDayTotal(0);
                userIds.add(rankDTO.getCustomerId());
                rankingListDTOMap.put(rankDTO.getCustomerId(), rankDTO);
            }
        }
        // 日排行榜
        if (!userIds.isEmpty()) {
            Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
            Instant end = start.plus(1, ChronoUnit.DAYS);
            List<RankDTO> list = rankService.findList(start, end, userIds);
            for (RankDTO rankDTO : list) {
                rankingListDTOMap.get(rankDTO.getCustomerId()).setDayTotal(rankDTO.getSumTotal());
            }
        }
        return rank;
    }
}
